package com.rockcent.third.helper;

import com.rockcent.common.common.BusinessException;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.MallMemberStatus;
import com.rockcent.mall.lib.domain.enumclass.MerchantStatus;
import com.rockcent.mall.lib.domain.enumclass.SystemType;
import com.rockcent.mall.lib.repository.*;
import com.rockcent.service.MerchantSrv;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by DK on 16/12/27.
 */
@Component
public class MallHelper {

    @Autowired
    private CateTemplateRepository cateTemplateRepository;

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private CodeHelper codeHelper;
    @Autowired
    private MerchantRepository merchantRepository;
    @Autowired
    private SysRolePermissionRepository sysRolePermissionRepository;
    @Autowired
    private SysUserRoleRepository sysUserRoleRepository;
    @Autowired
    private MerchantFundRepository merchantFundRepository;
    @Autowired
    private ChannelRepository channelRepository;
    @Autowired
    private ChannelCategoryRepository channelCategoryRepository;
    @Autowired
    private ChannelHelper channelHelper;
    @Autowired
    private MarketMerchantRepository marketMerchantRepository;
    @Autowired
    private MerchantCertifyRepository merchantCertifyRepository;
    @Autowired
    private MerchantChannelStatisticsRepository merchantChannelStatisticsRepository;
    @Autowired
    private MallMemberPayStandardRepository mallMemberPayStandardRepository;
    @Autowired
    private MallMemberRepository mallMemberRepository;
    @Autowired
    private AuthUserResourceDefaultRepository authUserResourceDefaultRepository;
    @Autowired
    private AuthUserResourceRepository authUserResourceRepository;
    @Autowired
    private UserMallRepository userMallRepository;
    @Autowired
    private MallFinancialSettingsRepository mallFinancialSettingsRepository;
    @Autowired
    private MerchantSrv merchantSrv;
    @Autowired
    private UserMerchantRepository userMerchantRepository;


    /**
     * 创建平台会员
     * @param mallId 平台ID
     * @return
     */
    public MallMember saveMallMember(Long mallId){
        MallMember mallMember = new MallMember();
        mallMember.setMallId(mallId);
        mallMember.setStatus(MallMemberStatus.NOT_MEMBER);
        mallMember.setBalance(BigDecimal.ZERO);
        mallMember.setSettlementDate("1");
        mallMember = mallMemberRepository.save(mallMember);
        return mallMember;
    }

    /**
     * 创建平台支付标准协议
     * @param mallId 平台ID
     */
    public void saveMallPayStandard(Long mallId, Long mallMemberId){
        MallMemberPayStandard mallPayStandard = new MallMemberPayStandard();
        mallPayStandard.setMallId(mallId);
        mallPayStandard.setBaseServiceFee( BigDecimal.valueOf(1000.00));
        mallPayStandard.setBaseServiceFeeNum("1");
        mallPayStandard.setBusinessServiceFee( BigDecimal.valueOf(10));
        mallPayStandard.setBusinessServiceFeeNum("1");
        mallPayStandard.setDealResellRate("0.006");
        mallPayStandard.setMallMemberId(mallMemberId);
        mallMemberPayStandardRepository.save(mallPayStandard);
    }

    /**
     * 角色权限
     * @param roleId 角色ID
     * @param permissionId 权限ID
     * @param mallId 平台ID
     */
    public void saveRolePermission(Long roleId, Long permissionId, Long mallId) {
        SysRolePermission sysRolePermission = new SysRolePermission();
        sysRolePermission.setPermissionId(permissionId);
        sysRolePermission.setMallId(mallId);
        sysRolePermission.setRoleId(roleId);
        sysRolePermissionRepository.save(sysRolePermission);
    }

    /**
     * 平台角色
     * @param roleId 角色ID
     * @param mallId 平台ID
     * @param userId 用户ID
     */
    public void saveUserRole(Long roleId, Long mallId, Long userId) {
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setRoleId(roleId);
        sysUserRole.setMallId(mallId);
        sysUserRole.setUserInfoId(userId);
        sysUserRoleRepository.save(sysUserRole);
    }

    /**
     * 平台品类模板
     * @param mallId 平台ID
     */
    public void saveCateTemplates(Long mallId) {
        List<CateTemplate> cateTemplates = cateTemplateRepository.findByIsDelete(Whether.NO);
        for (int i = 0; i < cateTemplates.size(); i++) {
            CateTemplate cateTemplate = cateTemplates.get(i);
            Category category = new Category();
            category.setName(cateTemplate.getName());
            category.setIconUrl(cateTemplate.getIconUrl());
            category.setDisplayOrderId(cateTemplate.getSort());
            category.setMallId(mallId);
            category.setVisible(Boolean.FALSE);
            categoryRepository.save(category);
        }
    }


    public Merchant saveMerchant(UserInfo userInfo, Mall mall, String shopName) throws Exception {
        // 保存商家信息
        Merchant merchant = new Merchant();
        merchant.setMallId(mall.getId());
        merchant.setName(shopName);
        if (StringUtils.isBlank(shopName)) {
            merchant.setName(userInfo.getUsername() + "_" + mall.getId());
        }
        merchant.setMerchantRegisterType(userInfo.getRegisterType());
        merchant.setStatus(MerchantStatus.UNVERIFY);
        merchant.setUserInfoId(userInfo.getId());
        String saleCode = codeHelper.genMerchantSaleCode();
        merchant.setSalesCode(saleCode);
        merchant = merchantRepository.save(merchant);

        //商家认证信息
        MerchantCertify merchantCertify = new MerchantCertify();
        merchantCertify.setMallId(mall.getId());
        merchantCertify.setAuditRemark("通过");
        merchantCertify.setCompanyName(mall.getCompanyName());
        merchantCertify.setMerchantId(merchant.getId());
        merchantCertify.setUserInfoId(userInfo.getId());
        merchantCertify.setEmail(userInfo.getEmail());
        merchantCertify.setContactPhone(userInfo.getMobile());
        merchantCertifyRepository.save(merchantCertify);

        //分销市场协议签订
        MarketMerchant marketMerchant = marketMerchantRepository.findByMerchantIdAndMallId(merchant.getId(), mall.getId());
        if (marketMerchant == null) {
            marketMerchant = new MarketMerchant();
            marketMerchant.setMallId(mall.getId());
            marketMerchant.setMerchantId(merchant.getId());
        }
        marketMerchant.setSaleProtocolStatus(true);
        marketMerchantRepository.save(marketMerchant);

        //  创建一个资金账号
        MerchantFund merchantFund = merchantFundRepository.findByMallIdAndMerchantId(merchant.getMallId(), merchant.getId());
        if (merchantFund == null) {
            merchantFund = new MerchantFund();
            merchantFund.setMallId(merchant.getMallId());
            merchantFund.setMerchantId(merchant.getId());
            merchantFund = merchantFundRepository.save(merchantFund);
            if (merchantFund.getId() == null) {
                throw new BusinessException("创建商户资金账户失败");
            }
            merchant.setMerchantFundId(merchantFund.getId());
            merchant = merchantRepository.save(merchant);
        }

        //创建商家权限账号
        merchantSrv.saveUserMerchant(merchant, userInfo.getUsername());

        // 创建系统默认渠道 默认自有渠道,默认平台渠道
        Channel channel = channelRepository.findByMerchantIdAndName(merchant.getId(), Channel.DEFAULT_SELF_CHANNEL_NAME);
        if (channel == null) {
            Channel platformChannel = channelHelper.create(merchant, Channel.DEFAULT_PLATFORM_CHANNEL_NAME, Channel.DEFAULT_PLANFORM_CHANNEL_NUM);
            platformChannel = channelRepository.save(platformChannel);
            channelCategoryRepository.save(platformChannel.getId(), Channel.DEFAULT_CATEGORY_ID);
            MerchantChannelStatistics selfStatistics = new MerchantChannelStatistics();
            selfStatistics.setChannelId(platformChannel.getId());
            selfStatistics.setMallId(merchant.getMallId());
            selfStatistics.setMerchantId(merchant.getId());
            merchantChannelStatisticsRepository.save(selfStatistics);

            Channel selfChannel = channelHelper.create(merchant, Channel.DEFAULT_SELF_CHANNEL_NAME, Channel.DEFAULT_SELF_CHANNEL_NUM);
            selfChannel = channelRepository.save(selfChannel);
            channelCategoryRepository.save(selfChannel.getId(), Channel.DEFAULT_CATEGORY_ID);
            MerchantChannelStatistics statistics = new MerchantChannelStatistics();
            statistics.setChannelId(selfChannel.getId());
            statistics.setMallId(merchant.getMallId());
            statistics.setMerchantId(merchant.getId());
            merchantChannelStatisticsRepository.save(statistics);
        }

        return merchant;

    }

    public Merchant save(UserInfo userInfo, Mall mall, String shopName) throws Exception {
        // 保存商家信息
        Merchant merchant = new Merchant();
        merchant.setMallId(mall.getId());
        merchant.setName(shopName);
        if (StringUtils.isBlank(shopName)) {
            merchant.setName(userInfo.getUsername() + "_" + mall.getId());
        }
        merchant.setMerchantRegisterType(userInfo.getRegisterType());
        merchant.setStatus(MerchantStatus.UNVERIFY);
        merchant.setUserInfoId(userInfo.getId());
        String saleCode = codeHelper.genMerchantSaleCode();
        merchant.setSalesCode(saleCode);
        merchant = merchantRepository.save(merchant);

        //添加授权
        this.saveRolePermission(1L, 1L, mall.getId());
        this.saveUserRole(1L, mall.getId(), userInfo.getId());
        return merchant;

    }

    //添加平台默认菜单权限
    public void saveAuthResource(Mall mall, String userName) {
        //设置平台在其平台为超级管理员
        UserMall userMall = userMallRepository.findByMallIdAndUserId(mall.getId(), mall.getUserInfoId());
        if (userMall == null) {
            userMall = new UserMall();
            userMall.setMallId(mall.getId());
            userMall.setIsSuperAdmin(Whether.YES);
            userMall.setName(mall.getName());
            userMall.setUserId(mall.getUserInfoId());
            userMall.setUsername(userName);
            userMallRepository.save(userMall);
        }
        //菜单权限
        List<AuthUserResource> authUserResourceList = authUserResourceRepository.findByMallId(mall.getId());
        authUserResourceRepository.delete(authUserResourceList);
        //添加平台默认菜单权限
        List<AuthUserResourceDefault> authUserResourceDefaultList = authUserResourceDefaultRepository.findBySystemType(SystemType.MALL);
        if (authUserResourceDefaultList != null && authUserResourceDefaultList.size() > 0) {
            for (AuthUserResourceDefault resourceDefault: authUserResourceDefaultList) {
                AuthUserResource authUserResource = new AuthUserResource();
                authUserResource.setUserId(mall.getUserInfoId());
                authUserResource.setResourceId(resourceDefault.getResourceId());
                authUserResource.setResourceParentId(resourceDefault.getResourceParentId());
                authUserResource.setMallId(mall.getId());
                authUserResourceRepository.save(authUserResource);
            }
        }
    }

    //添加平台财务设置
    public  void saveMallFinancialSettings(Long mallId){
        MallFinancialSettings mallFinancialSettings = mallFinancialSettingsRepository.findTop1ByMallIdAndIsDeleteOrderByLastUpdatedDesc(mallId, Whether.NO);
        if (mallFinancialSettings == null) {
            mallFinancialSettings = new MallFinancialSettings();
            mallFinancialSettings.setMallId(mallId);
            mallFinancialSettings.setBaseServiceFee(BigDecimal.ZERO);
            mallFinancialSettings.setProbationDays(0L);
            mallFinancialSettings.setBusinessServiceFeeRate(new BigDecimal(Mall.DEFAULT_SERVER_RATE));
            mallFinancialSettings.setShareFeeRate(new BigDecimal(Mall.DEFAULT_SHARE_RATE));
            mallFinancialSettingsRepository.save(mallFinancialSettings);
        }
    }

}
